/**
 * Module dependencies.
 */
var http = require("http");
var https = require("https");
var fs = require("fs");
var express = require('express')
    , path = require('path')
    , streams = require('./app/streams.js')();

var favicon = require('serve-favicon')
    , logger = require('morgan')
    , methodOverride = require('method-override')
    , bodyParser = require('body-parser')
    , errorHandler = require('errorhandler');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon(__dirname + '/public/images/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
    app.use(errorHandler());
}

// Configuare https
const httpsOption = {
    key: fs.readFileSync("./site.key"), // pss: 99999999
    cert: fs.readFileSync("./final.crt"),
    rejectUnauthorized: false,
}

// routing
require('./app/routes.js')(app, streams);
// 关于node服务器启动后局域网无法访问问题
// app.server = app.listen(端口号,IP地址,函数)
// host：IP地址，IPv4地址，设置为 0.0.0.0 或者本机ip地址
// var server = app.listen(app.get('port'), "172.16.251.204", function () {
//     console.log('Express server listening on port ' + app.get('port'));
// });
// var server = https.createServer(httpsOption, app).listen(app.get('port'), "172.16.251.204", function () {
//     console.log('Express server listening on port ' + app.get('port'));
// });
var serverIp = "172.16.251.204";
// var https = https.createServer(httpsOption, function (req, res) {
//     // res.writeHead(200);
//     // res.end("Hello World!");
//
// }).listen(3443, serverIp, function () {
//     console.log('https://0.0.0.0:3443/');
//     // console.log('Express server listening on port ' + app.get('port'));
// });
app.listen = function () {
    var server = https.createServer(httpsOption, this)
    return server.listen.apply(server, arguments)
}
// http
var server = app.listen(app.get('port'), serverIp, function () {
    console.log('Express server listening on port ' + app.get('port'));
});

var io = require('socket.io').listen(server);
/**
 * Socket.io event handling
 */

require('./app/socketHandler.js')(io, streams);